package cn.com.jslh.boarpro.main.presenter;

import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.blankj.utilcode.util.SPUtils;
import net.idik.lib.slimadapter.SlimAdapter;
import net.idik.lib.slimadapter.SlimAdapterEx;
import net.idik.lib.slimadapter.SlimInjector;
import net.idik.lib.slimadapter.viewinjector.IViewInjector;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import cn.com.jslh.boarpro.R;
import cn.com.jslh.boarpro.base.BaseApplication;
import cn.com.jslh.boarpro.main.contract.SearchContract;
import cn.com.jslh.boarpro.main.model.SearchModelImpl;
import cn.com.jslh.boarpro.main.view.SearchResultActivity;
import cn.com.jslh.boarpro.util.StartActivityUtil;
import cn.com.jslh.boarpro.util.WebService;
import cn.com.jslh.boarpro.util.search.DateSearchItem;
import cn.com.jslh.boarpro.util.search.RemarkSearchItem;
import cn.com.jslh.boarpro.util.search.SearchItem;
import cn.com.jslh.boarpro.util.search.SearchItemFactory;
import cn.com.jslh.boarpro.util.search.SelectSearchItem;
import cn.com.jslh.boarpro.util.search.TextSearchItem;
import cn.com.jslh.boarpro.util.timedialog.DatePickerListener;
import cn.com.jslh.boarpro.util.timedialog.DateChoseDialogUtil;

/**
 * Created by Administrator on 2017/11/10.
 */

public class SearchPresenterImpl implements SearchContract.Presenter {
    private SearchContract.View view;
    private Context context;
    private SearchContract.Model model;
    public static String SearchType;
    private SlimAdapterEx adapter;

    public SearchPresenterImpl(Context context, SearchContract.View view) {
        view.setPresenter(this);
        this.context = context;
        this.view = view;
        model = new SearchModelImpl();
    }


    @Override
    public void start() {
        model.getSearchInitInfo(context, SearchType, new WebService.NetSuccessListener() {
            @Override
            public void Success(String s) throws JSONException {
                JSONArray jsonArray = new JSONArray(s);
                List<Object> datas = new ArrayList<>();
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    if (!jsonObject.has("retrievetype"))
                        return;
                    SearchItem searchItem = null;
                    switch (jsonObject.getString("retrievetype")) {
                        case "remark":
                            searchItem = (SearchItem) SearchItemFactory.getSearchItem(RemarkSearchItem.class);
                            break;
                        case "txt":
                            searchItem = (SearchItem) SearchItemFactory.getSearchItem(TextSearchItem.class);
                            break;
                        case "date":
                            searchItem = (SearchItem) SearchItemFactory.getSearchItem(DateSearchItem.class);
                            break;
                        case "select":
                            searchItem = (SearchItem) SearchItemFactory.getSearchItem(SelectSearchItem.class);
                            break;
                    }
                    if (searchItem == null)
                        return;
                    searchItem.setTitle(jsonObject.getString("title"));
                    searchItem.setResult(jsonObject.getString("result"));
                    JSONArray matterarray = jsonObject.getJSONArray("matterarray");
                    List<SearchItem.MatterarrayBean> matterarrayBeans = new ArrayList<>();
                    for (int i1 = 0; i1 < matterarray.length(); i1++) {
                        JSONObject jsonObject1 = matterarray.getJSONObject(i1);
                        SearchItem.MatterarrayBean matterarrayBean = new SearchItem.MatterarrayBean();
                        matterarrayBean.setSELNAME(jsonObject1.getString("SELNAME"));
                        matterarrayBean.setSELID(jsonObject1.getString("SELID"));
                        matterarrayBeans.add(matterarrayBean);
                    }
                    searchItem.setMatterarray(matterarrayBeans);
                    searchItem.setKey(jsonObject.getString("key"));
                    searchItem.setIsview(jsonObject.getString("isview"));
                    searchItem.setIsrequire(jsonObject.getString("isrequire"));
                    searchItem.setPlaceholder(jsonObject.getString("placeholder"));
                    searchItem.setRetrievetype(jsonObject.getString("retrievetype"));
                    datas.add(searchItem);
                }
                adapter.updateData(datas).notifyDataSetChanged();
            }
        });
    }

    @Override
    public void bindRV(RecyclerView recyclerView) {
        adapter = SlimAdapter.create(SlimAdapterEx.class)
                .enableDiff()
                .enableEmptyView(context, R.layout.empty_layout)
                .registerDefault(R.layout.item_remark_layout, new SlimInjector() {
                    @Override
                    public void onInject(Object data, IViewInjector injector) {

                    }
                })
                .register(R.layout.item_remark_layout, new SlimInjector<RemarkSearchItem>() {
                    @Override
                    public void onInject(RemarkSearchItem data, IViewInjector injector) {
                        injector.text(R.id.title, data.getTitle()).text(R.id.context, data.getPlaceholder());
                    }
                })
                .register(R.layout.item_txt_layout, new SlimInjector<TextSearchItem>() {
                    @Override
                    public void onInject(final TextSearchItem data, IViewInjector injector) {
                        final int position = adapter.getData().indexOf(data);
                        injector.text(R.id.title, data.getTitle()).with(R.id.edittext, new IViewInjector.Action() {
                            @Override
                            public void action(View view) {
                                EditText editText = (EditText) view;
                                editText.setHint(data.getPlaceholder());
                                if(!data.getResult().equals("")){
                                    editText.setText(data.getResult());
                                }else {
                                    editText.setText("");
                                }
                                TextWatcher textWatcher = null;
                                if (view.getTag() == null) {
                                    textWatcher = new TextWatcher() {
                                        @Override
                                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                                        }

                                        @Override
                                        public void onTextChanged(CharSequence s, int start, int before, int count) {
//                                            ((TextSearchItem)adapter.getData().get(position)).setResult(s.toString());
                                        }

                                        @Override
                                        public void afterTextChanged(Editable s) {
                                            ((TextSearchItem) adapter.getData().get(position)).setResult(s.toString());
                                        }
                                    };
                                } else {
                                    textWatcher = (TextWatcher) view.getTag();
                                }
                                view.setTag(textWatcher);
                                editText.addTextChangedListener(textWatcher);
                            }
                        }).clicked(R.id.clear, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                ((TextSearchItem) adapter.getData().get(position)).setResult("");
                                adapter.notifyDataSetChanged();
                            }
                        });
                    }
                })
                .register(R.layout.item_date_layout, new SlimInjector<DateSearchItem>() {
                    @Override
                    public void onInject(DateSearchItem data, IViewInjector injector) {
                        final int position = adapter.getData().indexOf(data);
                        String dataStr =data.getResult();
                        dataStr = dataStr.equals("")?data.getPlaceholder():dataStr;
                        injector.text(R.id.title, data.getTitle())
                                .text(R.id.choseDate, dataStr)
                                .clicked(R.id.choseDate, new View.OnClickListener() {
                                    @Override
                                    public void onClick(final View v) {
                                        DateChoseDialogUtil.showTimeDialog(v.getContext(), new DatePickerListener() {
                                            @Override
                                            public void picker(String date) {
                                                ((DateSearchItem) adapter.getData().get(position)).setResult(date);
                                                ((TextView) v).setText(date);
                                            }
                                        });
                                    }
                                })
                                .clicked(R.id.clear, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        ((DateSearchItem) adapter.getData().get(position)).setResult("");
                                        adapter.notifyDataSetChanged();
                                    }
                                });
                    }
                })
                .register(R.layout.item_select_layout, new SlimInjector<SelectSearchItem>() {
                    @Override
                    public void onInject(SelectSearchItem data, IViewInjector injector) {
                        final int position = adapter.getData().indexOf(data);
                        final List<SearchItem.MatterarrayBean> items = data.getMatterarray();
                        String dataStr =data.getResult();
                        if(dataStr.equals("")){
                            dataStr =data.getPlaceholder();
                        }
                        final String[] itemStrs = new String[items.size()];
                        for (int i = 0; i < items.size(); i++) {
                            SearchItem.MatterarrayBean matterarrayBean = items.get(i);
                            itemStrs[i] = matterarrayBean.getSELNAME();
                            if(!dataStr.equals("")&&dataStr.equals(matterarrayBean.getSELID())){
                                dataStr =matterarrayBean.getSELNAME();
                            }
                        }

                        injector.text(R.id.title, data.getTitle())
                                .text(R.id.context,dataStr)
                                .clicked(R.id.context, new View.OnClickListener() {
                                    @Override
                                    public void onClick(final View v) {
                                        new AlertDialog.Builder(v.getContext())
                                                .setItems(itemStrs, new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        ((SelectSearchItem) adapter.getData().get(position)).setResult(items.get(which).getSELID());
                                                        ((TextView) v).setText(items.get(which).getSELNAME());
                                                    }
                                                }).show();
                                    }
                                })
                                .clicked(R.id.clear, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        ((SelectSearchItem) adapter.getData().get(position)).setResult("");
                                        adapter.notifyDataSetChanged();
                                    }
                                });
                    }
                })
                .attachTo(recyclerView);
    }

    @Override
    public void subData() {
        if (adapter == null || adapter.getData() == null || adapter.getData().size() == 0)
            return;
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("userID", SPUtils.getInstance().getString(BaseApplication.FUSERID));
            jsonObject.put("lineID", SPUtils.getInstance().getString(BaseApplication.FLINEID));
            jsonObject.put("searchType", SearchType);
            for (int i = 0; i < adapter.getData().size(); i++) {
                SearchItem searchItem = (SearchItem) adapter.getData().get(i);
                jsonObject.put(searchItem.getKey(), searchItem.getResult());
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        model.subData(context, jsonObject, new WebService.NetSuccessListener() {
            @Override
            public void Success(String s) throws JSONException {
                JSONArray jsonArray = new JSONArray(s);
                if (jsonArray.length() > 0) {
                    new StartActivityUtil.Builder(context, SearchResultActivity.class)
                            .addValue("json", s)
                            .build();
                }
            }
        });
    }
}
